package com.sojson.config.datasource;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties;
import com.alibaba.druid.util.Utils;
import com.sojson.util.ExpUtil;
import com.sojson.util.param.ParamUtil;
import com.sojson.util.token.Token;
import com.sojson.util.token.TokenUtil;

/**
 * 德鲁伊配置
 * 
 * @author liu
 * @date 2021-07-04
 */
@Configuration
public class DruidConfig {

    /** druid监控页面路径 */
    String druidUrl = "/druid";

    /**
     * 去除监控页面底部的广告
     */
    @Bean
    @ConditionalOnProperty(name = "spring.datasource.druid.statViewServlet.enabled", havingValue = "true")
    public FilterRegistrationBean<Filter> removeDruidFilterRegistrationBean(DruidStatProperties properties) {
        // 获取web监控页面的参数
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        // 提取common.js的配置路径
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : druidUrl + "/*";
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        // 创建filter进行过滤
        Filter filter = new Filter() {
            @Override
            public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {}

            @Override
            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
                String tokenStr = null;

                // 获取token字符串
                HttpServletRequest httpServletRequest = (HttpServletRequest)request;
                Cookie[] cookies = httpServletRequest.getCookies();
                if (cookies != null && cookies.length > 0) {
                    for (Cookie cookie : cookies) {
                        if ("Admin-Token".equals(cookie.getName())) {
                            tokenStr = cookie.getValue();
                            break;
                        }
                    }
                }
                if (tokenStr == null) {
                    ExpUtil.throwEx("用户未登陆");
                }
                // 获取token
                Token token = TokenUtil.getTokenByClaimsStr(tokenStr);
                // 登录验证
                ParamUtil.verifyLogin(token);
                // 权限验证
                ParamUtil.verifyPerm(druidUrl);

                chain.doFilter(request, response);

                // 重置缓冲区，响应头不会被重置
                response.resetBuffer();
                // 获取common.js
                String text = Utils.readFromResource(filePath);
                // 正则替换banner, 除去底部的广告信息
                text = text.replaceAll("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }

            @Override
            public void destroy() {}
        };
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }

}